<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
%>
<div id="delivery_add_page" class="row-fluid" style="height: inherit;margin:0px">
    <form action="" class="form-horizontal" id="delivery_add_baseInfor" name="baseInfor" method="post" target="_ifr" style="border-bottom: solid 2px #3b73af;">
        <input type="hidden" id="delivery_add_id" name="shipLoadingId" value="${info.id}">
        <div class="row" style="margin:0;padding:0;">
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="delivery_add_licensePlate" >车牌号：</label>
                <div class="controls">
                    <div class="required" >
                        <input type="text" id="delivery_add_licensePlate" class="span10" name="licensePlate" value="${info.licensePlate }"  placeholder="车牌号" />
                    </div>
                </div>
            </div>
        </div>
        <div style="margin-bottom:5px;">
            <span class="btn btn-info" id="delivery_add_formSave">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
            <span class="btn btn-info" id="delivery_add_outformSubmit" onclick="outformSubmitBtn();">
		        <i class="ace-icon fa fa-check bigger-110"></i>&nbsp;提交
            </span>
        </div>
    </form>
    <div id="delivery_add_materialDiv" style="margin:10px;">
        <label class="inline" for="delivery_add_qaCode">质保单号：</label>
        <input type="text" id = "delivery_add_qaCode" name="qaCode" style="width:350px;margin-right:10px;" />
        <button id="delivery_add_addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
            <i class="icon-plus" style="margin-right:6px;"></i>添加
        </button>
    </div>
    <div id="delivery_add_grid-div-c" style="width:100%;margin:0px auto;">
        <div id="delivery_add_fixed_tool_div" class="fixed_tool_div detailToolBar">
            <div id="delivery_add___toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
        <table id="delivery_add_grid-table-c" style="width:100%;height:100%;"></table>
        <div id="delivery_add_grid-pager-c"></div>
    </div>
</div>
<iframe src="about:blank" name="_ifr" height="0" class="hidden"></iframe>
<script type="text/javascript" src="<%=path%>/static/js/techbloom/outstorage/delivery/delivery_add.js"></script>
<script type="text/javascript">
    var context_path = '<%=path%>';
    var oriData;      //表格数据
    var _grid;        //表格对象
    var selectData = 0;   //存放物料选择框中的值
    var selectParam = "";  //存放之前的查询条件

    function outformSubmitBtn(){
        if($('#delivery_add_baseInfor #delivery_add_id').val()==-1){
            layer.alert("请先保存单据");
            return;
        }else {
            //后台修改对应的数据
            layer.confirm("确定提交,提交之后数据不能修改", function () {
                $.ajax({
                    type:"POST",
                    url:context_path+"/deleiveryCon/subShiploading",
                    dataType:"json",
                    data:{id:$('#delivery_add_baseInfor #delivery_add_id').val()},
                    success:function(data){
                        if(data.result){
                            layer.closeAll();
                            layer.msg("提交成功",{icon:1,time:1200});
                            gridReload();
                        }else{
                            layer.alert(data.msg);
                        }
                    }
                })
            });
        }
    }

    //单据保存按钮点击事件
    $("#delivery_add_formSave").click(function(){
        if($('#delivery_add_baseInfor').valid()){
            //通过验证：获取表单数据，保存表单信息
            var formdata = $('#delivery_add_baseInfor').serialize();
            saveFormInfo(formdata);
        }
    });

    $("#delivery_add_baseInfor").validate({
        rules: {
            "delivery_add_licensePlate": {
                required: true,
            },
        },
        messages: {
            "delivery_add_licensePlate": {
                required: "请输入车牌号!",
            },
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        }
    })

    //清空物料多选框中的值
    function removeChoice(){
        $("#s2id_qaCode .select2-choices").children(".select2-search-choice").remove();
        $("#delivery_add_qaCode").select2("val","");
        selectData = 0;
    }

    $('[data-rel=tooltip]').tooltip();

    $("#delivery_add_qaCode").select2({
        placeholder : "请选择质保单号",//文本框的提示信息
        minimumInputLength : 0, //至少输入n个字符，才去加载数据
        allowClear : true, //是否允许用户清除文本信息
        multiple: true,
        closeOnSelect:false,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax : {
            url : context_path + '/deleiveryCon/getQaCode',
            dataType : 'json',
            delay : 250,
            data : function(term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                selectParam = term;
                return {
                    queryString : term, //联动查询的字符
                    pageSize : 15, //一次性加载的数据条数
                    pageNo : pageNo, //页码
                    time : new Date()
                    //测试
                }
            },
            results : function(data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results : res,
                        more : more
                    };
                } else {
                    return {
                        results : {
                            "id" : "0",
                            "text" : "没有更多结果"
                        }
                    };
                }

            },
            cache : true
        }
    });

    $("#delivery_add_qaCode").on("change",function(e){
        var datas=$("#delivery_add_qaCode").select2("val");
        selectData = datas;
        var selectSize = datas.length;
        if(selectSize>1){
            var $tags = $("#delivery_add_qaCode .select2-choices");
            var $choicelist = $tags.find(".select2-search-choice");
            var $clonedChoice = $choicelist[0];
            $tags.children(".select2-search-choice").remove();
            $tags.prepend($clonedChoice);
            $tags.find(".select2-search-choice").find("div").html(selectSize+"个被选中");
            $tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
            $tags.find(".select2-search-choice").find("a").attr("href","#");
            $tags.find(".select2-search-choice").find("a").attr("onclick","removeChoice();");
        }
        //执行select的查询方法
        $("#delivery_add_qaCode").select2("search",selectParam);
    });

    //工具栏
    $("#delivery_add___toolbar__-c").iToolBar({
        id:"delivery_add___tb__01",
        items:[
            {label:"删除", onclick:delDetail}
        ]
    });


    //初始化表格
    _grid =  $("#delivery_add_grid-table-c").jqGrid({
        url : context_path + "/deleiveryCon/detailList.do?id="+$("#delivery_add_id").val(),
        datatype : "json",
        colNames : [ "详情主键","质保单号","物料编码","发货单号","米数"],
        colModel : [
            {name : "id",index : "id",width : 20,hidden:true},
            {name : "qaCode",index:"qaCode",width : 20},
            {name : "materialCode",index:"materialCode",width : 20},
            {name : "shipNo",index:"ship_No",width : 20},
            {name : "meter",index:"meter",width : 20},
        ],
        rowNum : 20,
        rowList : [ 10, 20, 30 ],
        pager : "#delivery_add_grid-pager-c",
        sortname : "id",
        sortorder : "asc",
        altRows: true,
        viewrecords : true,
        autowidth:true,
        multiselect:true,
        multiboxonly: true,
        loadComplete : function(data){
            var table = this;
            setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
            oriData = data;
            $(window).triggerHandler("resize.jqGrid");
        },
        cellEdit: true,
        cellsubmit : "clientArray",
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#delivery_add_grid-table-c").navGrid("#delivery_add_grid-pager-c",{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd("#delivery_add_grid-pager-c",{
            caption:"",
            buttonicon:"ace-icon fa fa-refresh green",
            onClickButton: function(){
                $("#delivery_add_grid-table-c").jqGrid("setGridParam",
                    {
                        url:context_path + "/deleiveryCon/detailList.do?id="+$("#delivery_add_id").val(),
                    }
                ).trigger("reloadGrid");
            }
        });

    $(window).on("resize.jqGrid", function () {
        $("#delivery_add_grid-table-c").jqGrid("setGridWidth", $("#delivery_add_grid-div-c").width() - 3 );
        var height = $(".layui-layer-title",_grid.parents(".layui-layer")).height()+
                     $("#delivery_add_baseInfor").outerHeight(true)+$("#delivery_add_materialDiv").outerHeight(true)+
                     $("#delivery_add_grid-pager-c").outerHeight(true)+$("#delivery_add_fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
                     $("#gview_delivery_add_grid-table-c .ui-jqgrid-hbox").outerHeight(true);
                     $("#delivery_add_grid-table-c").jqGrid("setGridHeight",_grid.parents(".layui-layer").height()-height);
    });
    $(window).triggerHandler("resize.jqGrid");


    //添加质保单号
    function addDetail(){
        var id = $("#delivery_add_baseInfor #delivery_add_id").val();
        if(id=='-1'){
            layer.alert("请先保存表单信息！");
            return;
        }
        if(selectData!=0){
            //将选中的物料添加到数据库中
            $.ajax({
                type:"POST",
                url:context_path + "/deleiveryCon/saveShipLoadingDetail",
                data:{id:$("#delivery_add_baseInfor #delivery_add_id").val(),qaCodeIds:selectData.toString()},
                dataType:"json",
                success:function(data){
                    removeChoice();   //清空下拉框中的值
                    if(data.result!=null){
                        layer.alert(data.msg);
                        //重新加载详情表格
                        $("#delivery_add_grid-table-c").jqGrid("setGridParam",
                            {
                                postData: {qId:$("#delivery_add_baseInfor #delivery_add_id").val()} //发送数据  :选中的节点
                            }
                        ).trigger("reloadGrid");
                    }else{
                        layer.alert("添加失败");
                    }
                }
            });
        }else{
            layer.alert("请选择物料！");
        }
    }
</script>
